const jwt = require('jsonwebtoken');

function authMiddleware(req, res, next) {
  const token = req.headers['authorization'];
  if (!token) {
    return res.status(200).json({ 
      data:null,
      message: 'No token provided.',
      code:403
    });
  }

  jwt.verify(token, process.env.JWT_SECRET, (err, decoded) => {
    if (err) {
      return res.status(401).json({ 
        message: 'Failed to authenticate token.' 
      });
    }

    req.userId = decoded.userId;
    next();
  });
}

module.exports = authMiddleware;